package login;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import swimv2.session.LoginRemoteInterface;

public class LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	Object user = new Object();
	private static final long serialVersionUID = -3913781114977490384L;

	public LoginServlet() {
		super();
	}

	public static Context getInitialContext() throws NamingException {

		Properties prop = new Properties();
		prop.setProperty("java.naming.factory.initial",
				"org.jnp.interfaces.NamingContextFactory");
		prop.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
		prop.setProperty("java.naming.provider.url", "127.0.0.1:1099");
		return new InitialContext(prop);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int trovato;
		PrintWriter out;
		try {

			Context ctx = getInitialContext();
			HttpSession session = request.getSession();
			LoginRemoteInterface LRI = (LoginRemoteInterface) ctx
					.lookup("LogicaLogin/remote");
			String nome = request.getParameter("nomeutente");
			String pwd = request.getParameter("password");
			trovato = LRI.trovaAmministratore(nome,pwd);
			
			if (trovato == 1) {

				session.setAttribute("amministratore", user);
				out = response.getWriter();
				out.print("<h1>Trovato Amministratore!</h1><br>");

			} else if(trovato==0){
				trovato = LRI.trovaUtente(nome,pwd);
				out = response.getWriter();
				out.print(trovato);
				if (trovato == 0) {

					out = response.getWriter();
					out.print("<h1>Errore nell'inserimento di Id e Password!</h1><br>");
					out.print("<a href=\"/swimv2Client/index.jsp\"><b>Indietro</b></a><br><br>");

				} else {

					session.setAttribute("utente", user);
					out = response.getWriter();
					out.print("<h1>Trovato Utente!</h1><br>");
				}
			}
			else {
				out = response.getWriter();
				out.print("<h1>Trovato Niente!</h1><br>");
			}
		} catch (Exception e) {
			e.printStackTrace();
			out = response.getWriter();
			out.print("Login Errato!");
		}

	}

}
